<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="showAddDialog" size="small">
          添加机构
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="机构名称：">
            <el-input v-model="listQuery.name" class="input-width" placeholder="机构名称"></el-input>
          </el-form-item>
          <el-button type="primary" size="small" @click="handleSearchList()">查询</el-button>
        </el-form>
      </div>
    </el-card>
    <div class="table-container">
      <el-table ref="merchantTable" :data="list" style="width: 100%;" v-loading="listLoading" border :fit="true">
        <el-table-column label="ID" min-width="60" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="机构名称" align="center" min-width="100">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="机构简称" align="center" min-width="80">
          <template slot-scope="scope">{{ scope.row.code }}</template>
        </el-table-column>
        <el-table-column label="纳税人识别号" align="center" min-width="150">
          <template slot-scope="scope">{{ scope.row.tax_number }}</template>
        </el-table-column>
        <el-table-column label="所属省市" align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.full_areaname || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="沐浴露余额" align="center" min-width="80">
          <template slot-scope="scope">
            <span style="color: #67C23A; font-weight: bold;">{{ scope.row.balance }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="60" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="350" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 1" size="mini" type="danger"
              @click="handleStatusChange(scope.$index, scope.row)">禁用</el-button>
            <el-button v-else size="mini" type="success"
              @click="handleStatusChange(scope.$index, scope.row)">启用</el-button>
            <el-button size="mini" @click="showRechargeDialog(scope.row)">充值</el-button>
            <el-button size="mini" @click="showUpdateDialog(scope.row)">编辑</el-button>
            <el-button size="mini" @click="showPermissionDialog(scope.row)">应用权限</el-button>
            <el-button size="mini" @click="handleAdmin(scope.row)">管理员账号</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize" :page-sizes="[5, 10, 15]"
        :current-page.sync="listQuery.pageNum" :total="total">
      </el-pagination>
    </div>

    <!-- 添加机构对话框 -->
    <el-dialog title="添加机构" :visible.sync="addDialogVisible" width="50%" @close="resetForm('addForm')">
      <el-form ref="addForm" :model="addForm" label-width="120px">
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入机构名称"></el-input>
        </el-form-item>
        <el-form-item label="机构简称" prop="code">
          <el-input v-model="addForm.code" placeholder="请输入机构简称"></el-input>
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="tax_number">
          <el-input v-model="addForm.tax_number" placeholder="请输入纳税人识别号"></el-input>
        </el-form-item>
        <el-form-item label="机构地址" prop="district_id">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-select v-model="addForm.province_id" placeholder="选择省" clearable @change="onAddProvinceChange" :loading="addProvinceLoading" style="width: 100%;">
                <el-option v-for="province in addProvinces" :key="province.id" :label="province.name" :value="province.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="addForm.city_id" placeholder="选择市" clearable @change="onAddCityChange" :loading="addCityLoading" style="width: 100%;">
                <el-option v-for="city in addCities" :key="city.id" :label="city.name" :value="city.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="addForm.district_id" placeholder="选择区县" clearable :loading="addDistrictLoading" style="width: 100%;">
                <el-option v-for="district in addDistricts" :key="district.id" :label="district.name" :value="district.id"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入详细地址" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="是否开启" prop="status">
          <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm" :loading="addLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑机构对话框 -->
    <el-dialog title="编辑机构" :visible.sync="updateDialogVisible" width="50%" @close="resetForm('updateForm')">
      <div v-loading="updateAreaDataLoading" style="min-height: 300px;">
        <el-form ref="updateForm" :model="updateForm" label-width="120px">
          <el-form-item label="机构名称" prop="name">
            <el-input v-model="updateForm.name" placeholder="请输入机构名称"></el-input>
          </el-form-item>
          <el-form-item label="机构简称" prop="code">
            <el-input v-model="updateForm.code" placeholder="请输入机构简称"></el-input>
          </el-form-item>
          <el-form-item label="纳税人识别号" prop="tax_number">
            <el-input v-model="updateForm.tax_number" placeholder="请输入纳税人识别号"></el-input>
          </el-form-item>
          <el-form-item label="机构地址" prop="district_id" v-if="!updateAreaDataLoading">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-select v-model="updateForm.province_id" placeholder="选择省" clearable @change="onUpdateProvinceChange" :loading="updateProvinceLoading" style="width: 100%;">
                  <el-option v-for="province in updateProvinces" :key="province.id" :label="province.name" :value="province.id"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select v-model="updateForm.city_id" placeholder="选择市" clearable @change="onUpdateCityChange" :loading="updateCityLoading" style="width: 100%;">
                  <el-option v-for="city in updateCities" :key="city.id" :label="city.name" :value="city.id"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select v-model="updateForm.district_id" placeholder="选择区县" clearable :loading="updateDistrictLoading" style="width: 100%;">
                  <el-option v-for="district in updateDistricts" :key="district.id" :label="district.name" :value="district.id"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="updateForm.address" placeholder="请输入详细地址" style="width: 100%;"></el-input>
          </el-form-item>
          <el-form-item label="是否开启" prop="status">
            <el-switch v-model="updateForm.status" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm" :loading="updateLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog title="充值" :visible.sync="rechargeDialogVisible" width="40%">
      <el-form ref="rechargeForm" :model="rechargeForm" label-width="100px">
        <el-form-item label="机构名称">
          <el-input v-model="rechargeForm.merchant_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前余额">
          <el-input v-model="rechargeForm.current_balance" disabled></el-input>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model.number="rechargeForm.amount" placeholder="请输入充值金额" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRecharge" :loading="rechargeLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 应用权限对话框 -->
    <el-dialog title="应用权限" :visible.sync="permissionDialogVisible" width="800px">
      <div v-loading="permissionLoading" style="min-height: 300px;">
        <el-form ref="permissionForm" :model="permissionForm" label-width="100px">
          <el-form-item label="机构名称">
            <el-input v-model="permissionForm.merchant_name" disabled style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item label="权限设置">
            <div class="permission-grid">
              <el-checkbox-group v-model="permissionForm.menu_codes">
                <!-- 显示权限列表 -->
                <template v-if="menuList && menuList.length > 0">
                  <el-checkbox v-for="item in menuList" :key="item.menu_code" :label="item.menu_code"
                    class="permission-item">
                    {{ item.menu_name }}
                  </el-checkbox>
                </template>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPermission" :loading="permissionSaveLoading"
          style="width: 100px;">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, updateStatus, deleteMerchant, createMerchant, updateMerchant, rechargeMerchant, updatePermissions, getPermissions, getMenuList, getAddresses } from '@/api/merchant'

export default {
  name: 'merchantList',
  components: {},
  data() {
    return {
      listQuery: {
        name: null,
        pageNum: 1,
        pageSize: 10
      },
      list: null,
      total: null,
      listLoading: true,
      // 对话框状态
      addDialogVisible: false,
      updateDialogVisible: false,
      rechargeDialogVisible: false,
      permissionDialogVisible: false,
      // 按钮loading状态
      addLoading: false,
      updateLoading: false,
      rechargeLoading: false,
      permissionLoading: false,
      permissionSaveLoading: false,
      // 省市区loading状态
      addProvinceLoading: false,
      addCityLoading: false,
      addDistrictLoading: false,
      updateProvinceLoading: false,
      updateCityLoading: false,
      updateDistrictLoading: false,
      // 编辑对话框省市区数据加载状态
      updateAreaDataLoading: false,
      // 表单数据
      addForm: {
        name: '',
        code: '',
        tax_number: '',
        province_id: null,
        city_id: null,
        district_id: null,
        address: '',
        status: 1
      },
      updateForm: {
        id: '',
        name: '',
        code: '',
        tax_number: '',
        province_id: null,
        city_id: null,
        district_id: null,
        address: '',
        status: 1
      },
      // 省市区数据
      addProvinces: [],
      addCities: [],
      addDistricts: [],
      updateProvinces: [],
      updateCities: [],
      updateDistricts: [],
      rechargeForm: {
        merchant_id: '',
        merchant_name: '',
        current_balance: 0,
        amount: 0
      },
      permissionForm: {
        merchant_id: '',
        merchant_name: '',
        menu_codes: []
      },
      // 定义菜单列表，对应截图中显示的权限选项
      menuList: [] // 将从后端API获取
    }
  },
  created() {
    this.getList()
    this.loadProvinces('add')
    this.loadProvinces('update')
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.data
        this.total = response.data.total
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetSearch() {
      this.listQuery = {
        name: null,
        pageNum: 1,
        pageSize: 10
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleStatusChange(index, row) {
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 立即设置loading状态，让用户看到加载中
        this.listLoading = true
        var status = 1
        if (row.status == 1) {
          status = 0
        }
        updateStatus(row.id, { status: status }).then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getList()
        }).catch(() => {
          // 出错时也需要关闭loading
          this.listLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        })
      })
    },
    handleDelete(index, row) {
      this.$confirm('是否要删除该机构?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMerchant(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      })
    },
    // 显示添加机构对话框
    showAddDialog() {
      this.resetForm('addForm')
      this.addDialogVisible = true
    },

    // 显示编辑机构对话框
    showUpdateDialog(row) {
      this.updateForm = {
        id: row.id,
        name: row.name,
        code: row.code,
        tax_number: row.tax_number,
        province_id: null,
        city_id: null,
        district_id: row.area_id || null,
        address: row.address || '',
        status: row.status !== undefined && row.status !== null ? row.status : 1
      }
      
      // 如果有area_id，需要反向加载省市区数据
      if (row.area_id) {
        this.loadAreaDataForEdit(row.area_id)
      }
      
      this.updateDialogVisible = true
    },

    // 显示充值对话框
    showRechargeDialog(row) {
      this.rechargeForm = {
        merchant_id: row.id,
        merchant_name: row.name,
        current_balance: row.balance,
        amount: 0
      }
      this.rechargeDialogVisible = true
    },

    // 显示应用权限对话框
    showPermissionDialog(row) {
      this.permissionForm = {
        merchant_id: row.id,
        merchant_name: row.name,
        menu_codes: []
      }

      this.permissionDialogVisible = true
      this.permissionLoading = true

      // 同时加载权限列表和商户权限
      Promise.all([
        this.loadMenuList(),
        this.loadMerchantPermissions(row.id)
      ]).finally(() => {
        this.permissionLoading = false
      })
    },

    // 加载权限列表
    loadMenuList() {
      // 使用getMenuList API获取权限列表
      return getMenuList().then(response => {
        console.log('权限列表API返回:', response);
        if (response && response.data && response.code === 200) {
          console.log('权限列表数据:', response.data);
          // 确保数据是数组格式
          this.menuList = Array.isArray(response.data) ? response.data : [];
          // 强制更新视图
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        } else {
          console.error('权限列表API返回错误:', response);
          this.menuList = [];
        }
      }).catch(error => {
        console.error('获取权限列表失败:', error);
        this.menuList = [];
      });
    },

    // 加载商户已设置的权限
    loadMerchantPermissions(merchantId) {
      return getPermissions(merchantId).then(response => {
        // 直接使用后端返回的权限编码，不需要转换
        const mappedCodes = response.data || [];
        this.permissionForm.menu_codes = mappedCodes;

        // 为了确保数据响应式更新，使用$set强制更新视图
        this.$nextTick(() => {
          this.$set(this.permissionForm, 'menu_codes', [...this.permissionForm.menu_codes]);
        });
      }).catch(() => {
        // 错误处理，保持空数组
        this.permissionForm.menu_codes = [];
      });
    },

    // 管理员账号仍保持页面跳转
    handleAdmin(row) {
      this.$router.push({ path: '/merchant/admin', query: { merchant_id: row.id, merchant_name: row.name } })
    },

    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
      // 额外重置省市区数据，确保下次打开时为空
      if (formName === 'addForm') {
        this.addForm.province_id = null
        this.addForm.city_id = null
        this.addForm.district_id = null
        this.addForm.address = ''
        this.addCities = []
        this.addDistricts = []
      } else if (formName === 'updateForm') {
        this.updateForm.province_id = null
        this.updateForm.city_id = null
        this.updateForm.district_id = null
        this.updateForm.address = ''
        this.updateCities = []
        this.updateDistricts = []
      }
    },


    // 提交添加表单
    submitAddForm() {
      // 先检查必填字段
      if (!this.addForm.name) {
        this.$message.error('请输入机构名称');
        return;
      }


      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.addLoading = true
          createMerchant(this.addForm).then(() => {
            this.addLoading = false
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.addDialogVisible = false
            this.getList()
          }).catch((error) => {
            this.addLoading = false
            // 处理后端返回的错误，显示更友好的提示
            if (error.response && error.response.data && error.response.data.message) {
              // 将英文字段名转换为中文显示
              const errorMsg = error.response.data.message
                .replace('name field', '机构名称')
                .replace('code field', '机构简称')
                .replace('tax_number field', '纳税人识别号')
                .replace('province field', '省份')
                .replace('city field', '城市')
                .replace('district field', '区县')
                .replace('address field', '详细地址')
                .replace('is required', '不能为空');
              this.$message.error(errorMsg);
            } else {
              this.$message.error('添加失败，请重试');
            }
          })
        }
      })
    },

    // 提交编辑表单
    submitUpdateForm() {
      // 先检查必填字段
      if (!this.updateForm.name) {
        this.$message.error('请输入机构名称');
        return;
      }


      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          this.updateLoading = true
          updateMerchant(this.updateForm.id, this.updateForm).then(() => {
            this.updateLoading = false
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.updateDialogVisible = false
            this.getList()
          }).catch((error) => {
            this.updateLoading = false
            // 处理后端返回的错误，显示更友好的提示
            if (error.response && error.response.data && error.response.data.message) {
              // 将英文字段名转换为中文显示
              const errorMsg = error.response.data.message
                .replace('name field', '机构名称')
                .replace('code field', '机构简称')
                .replace('tax_number field', '纳税人识别号')
                .replace('province field', '省份')
                .replace('city field', '城市')
                .replace('district field', '区县')
                .replace('address field', '详细地址')
                .replace('is required', '不能为空');
              this.$message.error(errorMsg);
            } else {
              this.$message.error('修改失败，请重试');
            }
          })
        }
      })
    },

    // 提交充值
    submitRecharge() {
      if (this.rechargeForm.amount <= 0) {
        this.$message({
          type: 'error',
          message: '充值金额必须大于0!'
        })
        return
      }
      this.rechargeLoading = true
      // 修改type字段为整数类型，通常1表示充值操作
      rechargeMerchant(this.rechargeForm.merchant_id, { amount: this.rechargeForm.amount, type: 1 }).then(() => {
        this.rechargeLoading = false
        this.$message({
          type: 'success',
          message: '充值成功!'
        })
        this.rechargeDialogVisible = false
        this.getList()
      }).catch(() => {
        this.rechargeLoading = false
      })
    },

    // 提交权限设置
    submitPermission() {
      this.permissionSaveLoading = true
      // 直接使用数据库格式的权限编码提交，不需要转换
      updatePermissions(this.permissionForm.merchant_id, { menu_codes: this.permissionForm.menu_codes || [] }).then(() => {
        this.permissionSaveLoading = false
        this.$message({
          type: 'success',
          message: '权限设置成功!'
        })
        this.permissionDialogVisible = false
        this.getList()
      }).catch(() => {
        this.permissionSaveLoading = false
      })
    },

    // 加载省份列表
    loadProvinces(type) {
      const loadingKey = type === 'add' ? 'addProvinceLoading' : 'updateProvinceLoading'
      this[loadingKey] = true
      getAddresses({ level: 1 }).then(response => {
        if (type === 'add') {
          this.addProvinces = response.data
        } else {
          this.updateProvinces = response.data
        }
      }).finally(() => {
        this[loadingKey] = false
      })
    },

    // 添加表单 - 省份改变
    onAddProvinceChange(provinceId) {
      this.addForm.city_id = null
      this.addForm.district_id = null
      this.addCities = []
      this.addDistricts = []
      if (provinceId) {
        this.addCityLoading = true
        getAddresses({ level: 2, parent_id: provinceId }).then(response => {
          this.addCities = response.data
        }).finally(() => {
          this.addCityLoading = false
        })
      }
    },

    // 添加表单 - 城市改变
    onAddCityChange(cityId) {
      this.addForm.district_id = null
      this.addDistricts = []
      if (cityId) {
        this.addDistrictLoading = true
        getAddresses({ level: 3, parent_id: cityId }).then(response => {
          this.addDistricts = response.data
        }).finally(() => {
          this.addDistrictLoading = false
        })
      }
    },

    // 编辑表单 - 省份改变
    onUpdateProvinceChange(provinceId) {
      this.updateForm.city_id = null
      this.updateForm.district_id = null
      this.updateCities = []
      this.updateDistricts = []
      if (provinceId) {
        this.updateCityLoading = true
        getAddresses({ level: 2, parent_id: provinceId }).then(response => {
          this.updateCities = response.data
        }).finally(() => {
          this.updateCityLoading = false
        })
      }
    },

    // 编辑表单 - 城市改变
    onUpdateCityChange(cityId) {
      this.updateForm.district_id = null
      this.updateDistricts = []
      if (cityId) {
        this.updateDistrictLoading = true
        getAddresses({ level: 3, parent_id: cityId }).then(response => {
          this.updateDistricts = response.data
        }).finally(() => {
          this.updateDistrictLoading = false
        })
      }
    },

    // 编辑时加载省市区数据
    async loadAreaDataForEdit(districtId) {
      this.updateAreaDataLoading = true
      try {
        // 使用district_id参数，后端会返回完整的省市区信息
        const response = await getAddresses({ district_id: districtId })
        const data = response.data
        
        // 设置省市区ID
        this.updateForm.province_id = data.province_id
        this.updateForm.city_id = data.city_id
        this.updateForm.district_id = data.district_id
        
        // 设置城市和区县列表
        this.updateCities = data.cities || []
        this.updateDistricts = data.districts || []
      } catch (error) {
        console.error('加载省市区数据失败:', error)
        this.$message.error('加载省市区数据失败')
      } finally {
        this.updateAreaDataLoading = false
      }
    }
  }
}
</script>

<style>
.input-width {
  width: 203px;
}

/* 权限网格布局样式 */
.permission-grid {
  min-height: 200px;
  max-height: 300px;
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.permission-grid .el-checkbox-group {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px 20px;
  width: 100%;
}

.permission-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin: 0 !important;
}
</style>
